const errcode = require('../utils/errcode')
const Email = require('../utils/email')
const regex = require('../utils/regex')

exports.loginGithub = async ctx => {
  const { user } = ctx.state.github

  const unionid = user.id
  const username = user.login
  const nickname = user.name
  const email = user.email
  const sign = user.bio
  const avatar = user.avatar_url
  // console.log(user)

  const userId = await ctx.models.user.addOauthUser('github', {
    unionid,
    username,
    nickname,
    email,
    sign,
    avatar
  })

  await ctx.service.user.setLoginSession(ctx, userId)

  ctx.redirect('/', 302)
}

exports.getLoginInfo = async ctx => {
  const user = await ctx.getLoginUser()
  ctx.success(user)
}

exports.register = async ctx => {
  const {
    username,
    password,
    nickname,
    email,
    avatar,
    code
  } = ctx.request.body

  const data = {
    username: username ? username.trim() : '',
    password: password ? password.trim() : '',
    nickname: nickname ? nickname.trim() : '',
    email: email ? email.trim() : '',
    avatar: avatar ? avatar.trim() : null
  }

  if (!data.username || !data.password || !data.nickname || !data.email || !code) {
    return ctx.error(errcode.REQUIRED_PARAMS)
  }

  if (!regex.email.test(email)) {
    return ctx.error(errcode.INVALID_EMAIL)
  }

  const valid = await ctx.models.code.validateCode(email, code)

  if (valid !== 0) {
    return ctx.error(errcode.INVALID_CODE)
  }

  const user = await ctx.models.user.findOne({
    attrs: ['id'],
    where: {
      username: data.username
    }
  })

  if (user) return ctx.error(errcode.USER_EXISTS)

  const userId = await ctx.models.user.createUser(data)

  // await ctx.service.user.setLoginSession(ctx, userId)

  ctx.success({
    id: userId
  })
}

exports.login = async ctx => {
  const { username, password } = ctx.request.body

  if (!username || !password) {
    return ctx.error(errcode.REQUIRED_PARAMS)
  }

  const result = await ctx.models.user.validUser(username, password)

  if (!result.valid) {
    return ctx.error(result.msg)
  }

  const token = await ctx.service.user.setLoginSession(ctx, result.id)
  const user = await ctx.getLoginUser()

  ctx.success({
    token: token,
    user: user
  })
}

exports.sendCode = async ctx => {
  const email = ctx.request.body.email

  if (!email) return ctx.error(REQUIRED_PARAMS)
  if (!regex.email.test(email)) {
    return ctx.error(INVALID_EMAIL)
  }

  const { code } = await ctx.models.code.createCode(email)

  await Email.sendEmail({
    to: [email],
    subject: '【MarkDo】注册验证码',
    html: `欢迎使用服务，验证码${code}；如非本人操作，请检账号安全。`
  })

  // const valid = await ctx.models.code.validateCode(email, code)

  ctx.success()
}
